package com.ccys.cms.service.userManagement.impl;

import cn.hutool.core.util.ObjectUtil;
import com.ccys.cms.service.userManagement.FavouritePrescriptionDetailProductService;
import com.ccys.cms.service.userManagement.FavouritePrescriptionService;
import com.ccys.common.util.Kit;
import com.ccys.common.util.StringUtil;
import com.ccys.common.vo.ResponseResult;
import com.ccys.db.dto.userManagement.FavouritePrescriptionDetailDto;
import com.ccys.db.dto.userManagement.FavouritePrescriptionDto;
import com.ccys.db.entity.TblFavouritePrescription;
import com.ccys.db.entity.TblFavouritePrescriptionDetail;
import com.ccys.db.entity.TblFavouritePrescriptionDetailProduct;
import com.ccys.db.mapper.TblFavouritePrescriptionDetailMapper;
import com.ccys.db.mapper.TblFavouritePrescriptionDetailProductMapper;
import com.ccys.db.mapper.TblFavouritePrescriptionMapper;
import com.ccys.db.page.PageDto;
import com.ccys.db.rely.service.impl.BaseServiceImpl;
import com.ccys.db.service.BaseTblAuditTrailWebService;
import com.ccys.db.vo.userManagement.FavouritePrescriptionDetailPageQueryVo;
import com.ccys.db.vo.userManagement.FavouritePrescriptionPageQueryVo;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.List;
import java.util.Optional;

/**
 * @program: WhiteCoat
 * @description: 处方管理实现类
 * @author: ZhangJingCan
 * @create: 2023-12-22 09:44
 **/

@Service
public class FavouritePrescriptionServiceImpl extends BaseServiceImpl<TblFavouritePrescription> implements FavouritePrescriptionService {

    /**
     * 处方主表
     */
    @Resource
    private TblFavouritePrescriptionMapper tblFavouritePrescriptionMapper;

    /**
     * 处方产品表
     */
    @Resource
    private TblFavouritePrescriptionDetailMapper tblFavouritePrescriptionDetailMapper;

    /**
     * 处方产品的详情表
     */
    @Resource
    private TblFavouritePrescriptionDetailProductMapper tblFavouritePrescriptionDetailProductMapper;

    @Autowired(required = false)
    private BaseTblAuditTrailWebService baseTblAuditTrailWebService;

    @Autowired(required = false)
    private FavouritePrescriptionDetailProductService favouritePrescriptionDetailProductService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult saveFavouritePrescription(FavouritePrescriptionDto dto) {
        //校验字段
        Kit.allParamValid(dto, "name", "groupId");
        //这里是后台 - 由谁创建字段直接设置为1-后台创建 - 医生ID字段不用管
        dto.setIsDefault(1);
        //todo:这里有个order字段 - 暂时不知道用不用 -
        if(StringUtil.isNotEmpty(dto.getId())) {
            if (dto.getStatus() != null) {
                //保存状态修改日志
                baseTblAuditTrailWebService.saveStatusLog(dto, dto.getStatus());
                return ResponseResult.success("Modified successfully!");
            }
        }else {
            dto.setStatus(1);
        }
        //直接新增或修改并返回
        return ResponseResult.update(this.insertOrUpdate(dto));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult deleteFavouritePrescription(FavouritePrescriptionDto dto) {
        //判断
        if (ObjectUtil.isEmpty(dto.getId())) {
            return ResponseResult.error("Parameter Error!");
        }
        //准备实体类并赋值
        TblFavouritePrescription tblFavouritePrescription = new TblFavouritePrescription();
        tblFavouritePrescription.setId(dto.getId());
        tblFavouritePrescription.setDelFlag(1);
        //判断是否修改成功 - 返回不同状态
        if (tblFavouritePrescriptionMapper.updateByPrimaryKeySelective(tblFavouritePrescription) > 0) {
            return ResponseResult.success("Delete Successful!");
        }
        return ResponseResult.error("Delete Failed!");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateFavouritePrescriptionStatus(FavouritePrescriptionDto dto) {
        //校验
        if (ObjectUtil.isEmpty(dto.getId()) || ObjectUtil.isEmpty(dto.getStatus())) {
            return ResponseResult.error("Parameter Error!");
        }
        //准备数据修改
        TblFavouritePrescription tblFavouritePrescription = new TblFavouritePrescription();
        tblFavouritePrescription.setId(dto.getId());
        tblFavouritePrescription.setStatus(dto.getStatus());
        if (tblFavouritePrescriptionMapper.updateByPrimaryKeySelective(tblFavouritePrescription) > 0) {
            //保存状态修改日志
            baseTblAuditTrailWebService.saveStatusLog(dto, dto.getStatus());
            return ResponseResult.success("Modified successfully!");
        }
        return ResponseResult.error("Modification failed!");
    }

    @Override
    public ResponseResult<PageInfo<FavouritePrescriptionPageQueryVo>, Object> findPageFavouritePrescription(FavouritePrescriptionDto dto) {
        dto.setStatus(Optional.ofNullable(dto.getStatus()).filter(s -> s > -1 && s < 2).orElse(null));
        //开启分页
        PageDto.startPage();
        List<FavouritePrescriptionPageQueryVo> list = tblFavouritePrescriptionMapper.findPageFavouritePrescription(dto);
        PageInfo<FavouritePrescriptionPageQueryVo> info = new PageInfo<>(list);
        return ResponseResult.success(info);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult saveFavouritePrescriptionDetail(FavouritePrescriptionDetailDto dto) throws ParseException {
        //校验字段
        Kit.allParamValid(dto, "favouritePrescriptionId", "productId", "purchased", "list");
        //检查是否存在重复数据 - 这里指的未删除的
        Example example = new Example(TblFavouritePrescriptionDetail.class);
        Example.Criteria criteria = example.createCriteria()
                .andEqualTo("favouritePrescriptionId", dto.getFavouritePrescriptionId())
                .andEqualTo("productId", dto.getProductId())
                .andEqualTo("delFlag", 0);
        //判断如果是修改 - 排除自身
        if (ObjectUtil.isNotEmpty(dto.getId())) {
            criteria.andNotEqualTo("id", dto.getId());
        }
        //判断存在返回错误信息
        if (ObjectUtil.isNotEmpty(tblFavouritePrescriptionDetailMapper.selectByExample(example))) {
            return ResponseResult.error("This product already exists in this prescription");
        }
        //校验list里面的字段值
        for (TblFavouritePrescriptionDetailProduct product : dto.getList()) {
            Kit.allParamValid(product, "uomQuantity", "unit", "duration", "frequency", "durationUnit", "quantity", "stepOrder");
        }

        //以上校验都没问题 - 判断新增还是修改
        if (ObjectUtil.isEmpty(dto.getId())) {
            //新增
            if (tblFavouritePrescriptionDetailMapper.insertSelective(dto) > 0) {
                //处方的产品表添加成功 - 则开始添加处方产品的详情表数据
                List<TblFavouritePrescriptionDetailProduct> list = dto.getList();
                for (TblFavouritePrescriptionDetailProduct product : list) {
                    //处方产品的ID
                    product.setFavouritePrescriptionDetailId(dto.getId());
                    product.preInsert();
                }
                //操作产品处方的详情表
                favouritePrescriptionDetailProductService.insertAll(list);
                return ResponseResult.success("Successfully added data");
            }
            return ResponseResult.error("Failed to add data");
        } else {
            //修改 - 先修改处方产品表
            if (tblFavouritePrescriptionDetailMapper.updateByPrimaryKeySelective(dto) > 0) {
                //准备数据删除产品处方的详情表数据
                Example detailProductExample = new Example(TblFavouritePrescriptionDetailProduct.class);
                detailProductExample.createCriteria().andEqualTo("favouritePrescriptionDetailId", dto.getId());
                TblFavouritePrescriptionDetailProduct tblFavouritePrescriptionDetailProduct = new TblFavouritePrescriptionDetailProduct();
                tblFavouritePrescriptionDetailProduct.setDelFlag(1);
                //修改所有符合"favouritePrescriptionDetailId",dto.getId()的数据的delFlag为1 - 软删除
                tblFavouritePrescriptionDetailProductMapper.updateByExampleSelective(tblFavouritePrescriptionDetailProduct, detailProductExample);
                //取出list - 准备新增数据
                List<TblFavouritePrescriptionDetailProduct> list = dto.getList();
                for (TblFavouritePrescriptionDetailProduct product : list) {
                    //id不为空的时候 - 需要置空id
                    if (ObjectUtil.isNotEmpty(product.getId())) {
                        product.setId(null);
                    }
                    //设置处方产品数据的id
                    product.setFavouritePrescriptionDetailId(dto.getId());
                    product.preInsert();
                }
                //批量保存
                favouritePrescriptionDetailProductService.insertAll(list);
                return ResponseResult.success("Data modification successful");
            }
            return ResponseResult.error("Data modification failed");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult deleteFavouritePrescriptionDetail(FavouritePrescriptionDetailDto dto) {
        //判断
        if (ObjectUtil.isEmpty(dto.getId())) {
            return ResponseResult.error("Parameter Error!");
        }
        //准备实体类并赋值
        TblFavouritePrescriptionDetail detail = new TblFavouritePrescriptionDetail();
        detail.setId(dto.getId());
        detail.setDelFlag(1);
        //判断是否修改成功 - 返回不同状态
        if (tblFavouritePrescriptionDetailMapper.updateByPrimaryKeySelective(detail) > 0) {
            return ResponseResult.success("Delete Successful!");
        }
        return ResponseResult.error("Delete Failed!");
    }

    @Override
    public ResponseResult<PageInfo<FavouritePrescriptionDetailPageQueryVo>, Object> findPageFavouritePrescriptionDetail(FavouritePrescriptionDetailDto dto) {
        if (ObjectUtil.isEmpty(dto.getFavouritePrescriptionId())){
            return ResponseResult.error("Parameter abnormality");
        }
        //开启分页
        PageDto.startPage();
        List<FavouritePrescriptionDetailPageQueryVo> list = tblFavouritePrescriptionDetailMapper.findPageFavouritePrescriptionDetail(dto);
        PageInfo<FavouritePrescriptionDetailPageQueryVo> info = new PageInfo<>(list);
        return ResponseResult.success(info);
    }

}
